<?php


namespace app\admin\controller;


use think\facade\Db;

/**
 * 菜单规则控制器
 * Class Menu
 * @package app\admin\controller
 */
class Menu extends Base
{

    // 菜单列表
    public function lst()
    {
        return view('lst');
    }

    // 菜单列表数据
    public function listData()
    {
        $data  =  Db::name('auth_rule')->select();
        $count =  Db::name('auth_rule')->count();
        return table(getTree($data,0),$count);
    }

    // 添加菜单页面
    public function addView()
    {
        $auth = Db::name('auth_rule')->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        $auth = array2Level($auth);
        return view('add',['auth'=>$auth]);
    }

    // 添加提交
    public function addPost()
    {
        $auth_rule  = input('title');
        $status     = input('status');
        $name       = input('name');
        $pid        = input('pid');
        $res = Db::name('auth_rule')
            ->where('title', $auth_rule)
            ->find();
        if (empty($res)) {
            Db::name('auth_rule')
                ->insert(['title' => $auth_rule,'name'=>$name, 'pid'=>$pid,'status' => $status]);
            return  suc('添加成功');
        } else {
            return  err('菜单名重复');
        }
    }

    // 修改页面
    public function editView($id)
    {
        $data = Db::name('auth_rule')->find($id);
        $auth = Db::name('auth_rule')->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        $auth = array2Level($auth);
        return view('edit',['data'=>$data,'auth'=>$auth]);
    }

    // 修改提交
    public function editPost()
    {
        $auth_rule  = input('title');
        $status     = input('status');
        $id         = input('id');
        $name       = input('name');
        $pid        = input('pid');
        $res = Db::name('auth_rule')
            ->update(['title' => $auth_rule,'name'=>$name,'pid'=>$pid, 'status' => $status,'id'=>$id]);
        if ( $res !== false) {
            return  suc('编辑成功');
        } else {
            return  err('编辑失败');
        }
    }

    # 菜单删除
    public function del()
    {
        $id = input('id');
        # 查询是否有子菜单 有就先不删
        $child = Db::name('auth_rule')->where('pid',$id)->find();
        if ( !empty($child))
            return err('请先删除下级菜单');
        $rt = Db::name('auth_rule')->delete($id);
        if ($rt){
            return suc('删除成功');
        }else{
            return err('删除失败');
        }
    }

}